<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户列表" prop="exportUsernameList">
        <el-select v-model="queryParams.exportUsernameList" placeholder="请选择用户" multiple clearable>
          <el-option
            v-for="user in userList"
            :key="user.rybm"
            :label="user.mc"
            :value="user.mc"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="任务时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :clearable="false"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:task:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="conversionStorage"
          v-hasPermi="['system:task:convert']"
        >转换存储
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div style="height: 70vh; overflow: auto;">
      <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange" height="100%">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="序号" type="index" width="50" fixed/>
        <el-table-column label="人员姓名" align="center" prop="username" width="80" fixed/>
        <el-table-column label="组长姓名" align="center" prop="leader" width="80"/>
        <el-table-column label="任务完成时间" align="center" prop="taskTime" width="100"/>
        <el-table-column label="项目名称" align="center" prop="projectName" width="120"/>
        <el-table-column label="任务描述" align="left" prop="taskDescription" width="800">
          <template slot-scope="scope">
            <div style="white-space: pre-wrap;">{{ scope.row.taskDescription }}</div>
          </template>
        </el-table-column>
        <el-table-column label="消耗小时数" align="center" prop="useTime" width="100"/>
        <el-table-column label="任务类型" align="center" prop="taskType" width="100"/>
        <el-table-column label="任务ID" align="center" prop="rwid" width="100"/>
      </el-table>
    </div>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-input-number v-model="number" :min="1" :max="10" :step="1" size="mini"
                           label="请输入数字"></el-input-number>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            @click="insertRow"
            v-hasPermi="['system:task:insert']"
          >插入行
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <span style="color: red">【消耗小时数】不能为空，为空保存不上</span>
        </el-col>
      </el-row>
      <div id="example">
        <hot-table ref="hotTableComponent" :settings="hotSettings" :language="language">
        </hot-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="batchSave">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 认可或批量任何对话框 -->
    <el-dialog :title="approveTitle" :visible.sync="approveOpen" width="20%" append-to-body>
      <el-radio v-model="approveForm.approveType" label="YES">认可</el-radio>
      <el-radio v-model="approveForm.approveType" label="NO">不认可</el-radio>
      <br/>
      <br/>
      <el-slider v-model="approveForm.approvePercent" :min="0" :max="200" :step="10" :marks="marks" class="slider"
                 :format-tooltip="formatTooltip"></el-slider>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="executeApproveType">确 定</el-button>
        <el-button @click="cancelApproveType">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTask,
  delTask,
  listTaskByIds,
  batchSaveTask,
  approveTask,
  listUser,
  getTimeSystemTaskList,
  taskConversionStorage
} from "@/api/system/task";

import {HotTable} from "@handsontable/vue";
import "handsontable/dist/handsontable.full.css";
import {TextEditor} from 'handsontable/editors/textEditor';
import {registerAllModules} from 'handsontable/registry';
import {
  registerLanguageDictionary,
  zhCN
} from 'handsontable/i18n';

registerLanguageDictionary(zhCN);

// register Handsontable's modules
registerAllModules();

class CustomEditor extends TextEditor {
  createElements() {
    super.createElements();

    this.TEXTAREA = document.createElement('input');
    this.TEXTAREA.setAttribute('data-hot-input', true);
    this.textareaStyle = this.TEXTAREA.style;
    this.TEXTAREA_PARENT.innerText = '';
    this.TEXTAREA_PARENT.appendChild(this.TEXTAREA);
  }
}

export default {
  name: "Task",
  dicts: ['approve_type'],
  components: {
    HotTable
  },
  data() {
    return {
      hotSettings: {
        data: this.getDefaultTableData(),
        navigableHeaders: true,
        // 设置列标题
        colHeaders: ['ID', '人员姓名', '组长姓名', '任务开时间', '任务结束时间', '事项类型', '事项描述', '消耗小时数'],
        fixedColumnsStart: 3,
        // 设置列的宽度
        colWidths: [120, 120, 120, 120, 120, 120, 330, 120],
        // 设置列的高度
        columnHeaderHeight: 40,
        // 设置列高之后，列标题垂直居中显示
        afterGetColHeader: function (col, TH) {
          TH.style.verticalAlign = 'middle';
        },
        rowHeaders: true,
        height: '600',
        width: '100%',
        // 设置行的高度
        rowHeights: 40,
        // 设置行高之后，行标题垂直居中显示
        afterGetRowHeader: function (col, TH) {
          TH.style.verticalAlign = 'middle';
        },
        manualColumnResize: true,
        autoWrapRow: true,
        autoWrapCol: true,
        // selectionMode: 'multiple',
        hiddenColumns: {
          columns: [0],
          indicators: false,
        },
        filters: true,
        dropdownMenu: true,
        contextMenu: true,
        // contextMenu: {
        //   items: {
        //     'row_above': {
        //       name: '向上插入'
        //     },
        //     'row_below': {
        //       name: '向下插入'
        //     }
        //   }
        // },
        columns: [
          {data: 1, type: "text", className: 'htLeft htMiddle', editor: CustomEditor},
          {data: 2, type: "text", className: 'htLeft htMiddle', editor: CustomEditor},
          {data: 3, type: "text", className: 'htLeft htMiddle', editor: CustomEditor},
          {data: 4, type: "date", allowInvalid: false, className: 'htCenter htMiddle', dateFormat: 'YYYY-MM-DD'},
          {data: 5, type: "date", allowInvalid: false, className: 'htCenter htMiddle', dateFormat: 'YYYY-MM-DD'},
          {data: 6, type: "text", className: 'htLeft htMiddle', editor: CustomEditor},
          {data: 7, type: "text", className: 'htLeft htMiddle', editor: CustomEditor},
          {data: 8, type: "numeric", className: 'htRight htMiddle', editor: CustomEditor}
        ],
        licenseKey: 'non-commercial-and-evaluation'
      },
      language: 'zh-CN',
      number: 1,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 参数表格数据
      taskList: [],
      // 弹出层标题
      title: "",
      approveTitle: "任务认可",
      // 是否显示弹出层
      open: false,
      approveOpen: false,
      // 日期范围
      dateRange: this.getDefaultCurrentTime(),
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        exportUsernameList: [],
        beginTime: undefined,
        endTime: undefined,
        kl: '1',
        dlbm: '1',
        taskExportModelList: []
      },
      defaultApprovePercent: 100,
      defaultApproveType: "YES",
      marks: {
        0: '0%',
        50: '50%',
        100: '100%',
        150: '150%',
        200: '200%',
      },
      approveForm: {
        approvePercent: this.defaultApprovePercent,
        approveType: this.defaultApproveType,
      },
      // 单个认可时的id集合
      singleIds: [],
      // 为1时是单个认可，为2时是批量认可
      operateType: 1,
      userList: []
    };
  },
  created() {
    this.getUserList();
    this.getList();
  },
  methods: {
    getUserList() {
      listUser().then(response => {
          console.log(response)
          this.userList = response;
        }
      );
    },
    formatTooltip(val) {
      return `${val}%`;
    },
    getDefaultCurrentTime() {
      const currentDate = new Date();
      // 获取当前日期的年、月和日
      const currentYear = currentDate.getFullYear();
      const currentMonth = currentDate.getMonth() + 1;
      const currentDay = currentDate.getDate();
      // 当前起止时间
      const startTime = `${currentYear}-${currentMonth < 10 ? '0' + currentMonth : currentMonth}-01`;
      const endTime = `${currentYear}-${currentMonth < 10 ? '0' + currentMonth : currentMonth}-${currentDay < 10 ? '0' + currentDay : currentDay}`;
      return [startTime, endTime];
    },
    /** 查询参数列表 */
    getList() {
      this.loading = true;
      if (this.dateRange.length == 0) {
        let defaultCurrentTime = this.getDefaultCurrentTime();
        this.queryParams.beginTime = defaultCurrentTime[0];
        this.queryParams.endTime = defaultCurrentTime[1];
      } else {
        this.queryParams.beginTime = this.dateRange[0];
        this.queryParams.endTime = this.dateRange[1];
      }
      getTimeSystemTaskList(this.queryParams).then(response => {
          this.taskList = response;
          this.loading = false;
        }
      );
    },
    insertRow() {
      let len = this.$refs.hotTableComponent.hotInstance.getData().length;
      for (let i = 0; i < this.number; i++) {
        this.$refs.hotTableComponent.hotInstance.alter('insert_row_above', len + i);
      }
    },
    // 批量保存
    batchSave() {
      let datas = this.$refs.hotTableComponent.hotInstance.getData();
      let taskModelList = [];
      datas.forEach(data => {
        if (data[7]) {
          const taskModel = {
            "id": data[0],
            "username": data[1],
            "leader": data[2],
            "taskStartTime": data[3] + " 00:00:00",
            "taskEndTime": data[4] + " 00:00:00",
            "type": data[5],
            "description": data[6],
            "operateTime": data[7],
          };
          taskModelList.push(taskModel);
        }
      })
      if (taskModelList.length != 0) {
        batchSaveTask(taskModelList).then(response => {
          if (response.data) {
            this.getList();
            this.cancel();
          }
        });
      } else {
        this.cancel();
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      if (this.$refs.hotTableComponent) {
        this.$refs.hotTableComponent.hotInstance.loadData([]);
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 初始化认可
    initApproveType(row) {
      this.approveOpen = true;
      if (row.id != null) {
        this.approveForm.approveType = row.approveType || this.defaultApproveType;
        this.approveForm.approvePercent = (row.approvePercent && parseInt(row.approvePercent)) || this.defaultApprovePercent;
        this.singleIds = [];
        this.singleIds.push(row.id);
        this.operateType = 1;
      } else {
        this.approveForm.approveType = this.defaultApproveType;
        this.approveForm.approvePercent = this.defaultApprovePercent;
        this.operateType = 2;
      }
    },
    // 执行认可
    executeApproveType() {
      let taskIds = [];
      if (this.operateType == 1) {
        taskIds = this.singleIds;
      } else {
        taskIds = this.ids;
      }
      approveTask({
        "idsParam": {"ids": taskIds.join(",")},
        "approveType": this.approveForm.approveType,
        "approvePercent": this.approveForm.approvePercent
      }).then(response => {
        if (response.data) {
          this.cancelApproveType();
          this.getList();
        }
      });
    },
    cancelApproveType() {
      this.approveOpen = false;
    },
    changeApproveType() {
      if (!this.queryParams.approveType) {
        this.queryParams.approveType = null;
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = this.getDefaultCurrentTime();
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.multiple = !selection.length
    },
    getDefaultTableData() {
      return [];
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.title = "添加任务";
      if (this.$refs.hotTableComponent) {
        this.$refs.hotTableComponent.hotInstance.init();
        this.$refs.hotTableComponent.hotInstance.loadData(this.getDefaultTableData());
      }
    },
    handleUpdate() {
      this.open = true;
      this.title = "修改任务";
      const taskIds = this.ids;
      listTaskByIds(taskIds.join(',')).then(response => {
          if (response.data) {
            let datas = response.data;
            let arrays = [];
            datas.forEach(data => {
              let d = ['', data.id, data.username, data.leader, data.taskStartTime.substr(0, 10), data.taskEndTime.substr(0, 10), data.type, data.description, data.operateTime];
              arrays.push(d);
            })
            this.$refs.hotTableComponent.hotInstance.loadData(arrays);
          }
        }
      );
    },
    /** 删除按钮操作 */
    handleDelete() {
      const taskIds = this.ids;
      this.$modal.confirm('是否确认当前选中的任务吗？').then(function () {
        return delTask(taskIds.join(','));
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.queryParams.beginTime = this.dateRange[0];
      this.queryParams.endTime = this.dateRange[1];
      this.download('/api/system/test/exportTaskDetailList', {
        ...this.queryParams
      }, `task_${new Date().getTime()}.xlsx`)
    },
    // 转换存储
    conversionStorage() {
      let message = "";
      if (this.queryParams.exportUsernameList.length == 0) {
        message += "由于您没有选择用户，故会对所有用户";
      } else {
        message += "你选择的用户为【" + this.queryParams.exportUsernameList.join(", ") + "】";
      }
      message += "时间从【" + this.dateRange[0] + "】到【" + this.dateRange[1] + "】的任务会进行覆盖，是否继续？";
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        this.queryParams.beginTime = this.dateRange[0];
        this.queryParams.endTime = this.dateRange[1];
        taskConversionStorage(this.queryParams).then(response => {
            if (response) {
              this.$modal.msgSuccess("存储转换成功！");
              this.loading = false;
            }
          }
        );
      }).catch(() => {
      });
    }
  }
}
;
</script>


<style rel="stylesheet/scss" lang="scss">
.handsontable.htContextMenu {
  z-index: 3000 !important; /* 调整右键菜单的 z-index 值，!important用于确保优先级 */
}

.handsontable.htDropdownMenu {
  z-index: 3000 !important; /* 调整下拉菜单的 z-index 值，!important用于确保优先级 */
}

.slider .el-slider__button-tooltip {
  white-space: nowrap; /* 防止标记文本换行 */
}

</style>
